<template>
  <div class="health-container">
    <!-- 顶部查询 -->
    <div class="query-bar">
      <el-select
          v-model="query.relationType"
          placeholder="关系类型"
          clearable
          style="width: 120px"
      >
        <el-option label="配偶" value="配偶" />
        <el-option label="子女" value="子女" />
        <el-option label="其他" value="其他" />
      </el-select>

      <el-input
          v-model="query.realName"
          placeholder="老人姓名"
          clearable
          style="width: 160px; margin-left: 8px"
      />

      <el-button type="primary" @click="loadElderlyList" style="margin-left: 8px">
        查询
      </el-button>

      <el-button @click="resetQuery" style="margin-left: 8px">
        重置
      </el-button>
    </div>


    <div v-if="elderlyHealthSummary.length" class="section-title">
      <br>
    </div>
    <div class="card-grid-overview">
      <el-card
        v-for="elderly in elderlyHealthSummary"
        :key="elderly.userId"
        :class="{
    abnormal: elderly.hasUnhandledAlert || elderly.hasAbnormal,
    disabled: elderly.allHandled
  }"
        @click="openHealthDetailModal(elderly)"
    >
      <!-- 头像 -->
      <div class="avatar">
        <el-avatar :size="70" :src="elderly.avatarUrl" />
      </div>
      <!-- 姓名 -->
      <div class="name">{{ elderly.realName }}</div>
      <!-- 健康状态标签 -->
      <el-tag v-if="elderly.hasUnhandledAlert" type="danger">未处理预警</el-tag>
      <el-tag v-else-if="elderly.hasAbnormal" type="warning">健康数据异常</el-tag>
      <el-tag v-else type="success">正常</el-tag>
    </el-card>
    </div>

    <!-- 健康概览卡片（原逻辑保留） -->
    <div v-if="selectedElderly" class="elderly-profile">
      <el-card class="profile-card">
        <div class="profile-header">
          <div class="avatar">
            <el-avatar :size="60" :src="avatarUrl" />
          </div>
          <div class="info">
            <h3>{{ selectedElderly.realName }}</h3>
            <div class="meta">
              <span>{{ genderText }} | {{ age }}岁</span>
              <span>电话: {{ selectedElderly.phone }}</span>
            </div>
          </div>
        </div>
        <div class="health-summary">
          <div class="summary-item">
            <span class="label">身高</span>
            <span class="value">{{ selectedElderly.height || '--' }} cm</span>
          </div>
          <div class="summary-item">
            <span class="label">体重</span>
            <span class="value">{{ selectedElderly.weight || '--' }} kg</span>
          </div>
          <div class="summary-item">
            <span class="label">血型</span>
            <span class="value">{{ selectedElderly.bloodType || '--' }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 健康数据卡片（原逻辑保留） -->
    <div v-if="healthDataList.length > 0">
      <h3 class="section-title">健康监测数据</h3>
      <div class="card-grid">
        <el-card
            v-for="data in healthDataList"
            :key="data.recordId"
            class="data-card"
            :class="{ abnormal: !data.isNormal }"
        >
          <div class="card-header">
            <div class="title">{{ getTypeName(data.dataType) }}</div>
            <el-tag :type="data.isNormal ? 'success' : 'danger'" size="small">
              {{ data.isNormal ? '健康数据正常' : '健康数据异常' }}
            </el-tag>
          </div>
          <div class="card-body">
            <div class="value">
              {{ data.dataValue }}
              <span class="unit">{{ data.unit }}</span>
            </div>
          </div>
          <div class="card-footer">
            <el-icon><Clock /></el-icon>
            <span class="time">{{ formatTime(data.measureTime) }}</span>
          </div>
        </el-card>
      </div>
      <div class="pagination-wrapper">
        <el-pagination
            v-model:current-page="pageNum"
            :total="total"
            :page-size="pageSize"
            layout="prev, pager, next, total"
            @current-change="loadHealthData"
        />
      </div>
    </div>

<!--    <el-empty v-else description="暂无数据" />-->

    <el-dialog
        v-model="detailDialogVisible"
        :title="`${detailElderly.realName} - 健康详情`"
        width="70%"
    >
      <!-- 未处理预警 -->
      <div v-if="detailAlerts.length">
        <h3 style="color: #f56c6c;">未处理预警</h3>
        <div
            v-for="alert in detailAlerts"
            :key="alert.alertId"
            class="alert-item"
        >
          <span>{{ alert.alertContent }}</span>
          <el-button
              size="small"
              type="primary"
              @click="handleAlert(alert.alertId)"
          >标记已处理</el-button
          >
        </div>
        <el-divider />
      </div>

      <!-- 健康数据表格 -->
      <el-table :data="detailHealthData.list" style="width: 100%">
        <el-table-column prop="typeName" label="指标" />
        <el-table-column prop="dataValue" label="数值" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="deviceName" label="设备" />
        <el-table-column label="是否正常">
          <template #default="{ row }">
            <el-tag :type="row.isNormal ? 'success' : 'danger'">
              {{ row.isNormal ? '健康数据正常' : '健康数据异常' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          background
          layout="prev, pager, next"
          :total="detailHealthData.total"
          :page-size="detailHealthData.pageSize"
          @current-change="loadDetailHealth"
      />

      <template #footer>
        <el-button type="primary" @click="exportDetailExcel">健康数据导出 Excel</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, inject } from 'vue'
import axios from 'axios'
import * as XLSX from 'xlsx'
import dayjs from 'dayjs'
import { Clock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const BASE_URL = 'http://localhost:8080'
const token = localStorage.getItem('token')
const currentUser = inject('currentUser')


const elderlyList = ref([])
const selectedElderlyId = ref(null)
const selectedElderly = ref(null)
const healthDataList = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const query = ref({ relationType: '', realName: '' })

/* ---------- 新增：健康概览卡片 ---------- */
const elderlyHealthSummary = ref([])

/* ---------- 新增：健康详情弹窗 ---------- */
const detailDialogVisible = ref(false)
const detailElderly = ref({})
const detailAlerts = ref([])
const detailHealthData = ref({ list: [], total: 0, pageSize: 5 })

/* ---------- 工具 ---------- */
const typeMap = {
  1: '心率',
  2: '血压',
  3: '血糖',
  4: '血氧',
  5: '体温',
  6: '睡眠'
}

/* ----------  loadElderlyList ---------- */
const loadElderlyList = async () => {
  if (!currentUser.value?.userId) {
    ElMessage.error('用户未登录或登录已过期')
    return
  }
  loading.value = true
  try {
    const { data: res } = await axios.get(
        `${BASE_URL}/api/v1/family_user/elderly/boundElderly/search`,
        {
          params: { familyUserId: currentUser.value.userId, ...query.value },
          headers: { Authorization: `Bearer ${token}` }
        }
    )

    // 空值保护
    const list = res?.data || []
    if (!Array.isArray(list)) {
      console.warn('老人列表接口返回格式异常', res)
      return
    }

    elderlyList.value = list.map((e) => ({
      userId: e.elderlyUserId,
      realName: e.realName,
      relationType: e.relationType,
      avatarUrl: e.avatarUrl || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
    }))

    // 同步更新健康概览卡片
    elderlyHealthSummary.value = [...elderlyList.value]
    for (const e of elderlyHealthSummary.value) {
      // 未处理预警
      const { data: alertRes } = await axios.get(
          `${BASE_URL}/api/v1/health/alert/unhandled/${currentUser.value.userId}`,
          { headers: { Authorization: `Bearer ${token}` } }
      )
      e.hasUnhandledAlert = alertRes?.data?.some?.((a) => a.elderlyUserId === e.userId) ?? false

      // 异常健康数据
      const { data: healthRes } = await axios.get(`${BASE_URL}/api/v1/health/list`, {
        params: { elderlyUserId: e.userId, pageNum: 1, pageSize: 1 },
        headers: { Authorization: `Bearer ${token}` }
      })
      e.hasAbnormal = healthRes?.data?.list?.some?.((h) => h.isNormal === 0) ?? false
    }
  } catch (error) {
    console.error('获取老人列表失败', error)
    ElMessage.error('获取老人列表失败')
  } finally {
    loading.value = false
  }
}


/* ---------- loadHealthData ---------- */
const loadHealthData = async () => {
  if (!selectedElderlyId.value) return
  loading.value = true
  try {
    const { data: res } = await axios.get(`${BASE_URL}/api/v1/health/list`, {
      params: {
        elderlyUserId: selectedElderlyId.value,
        pageNum: pageNum.value,
        pageSize: pageSize.value
      },
      headers: { Authorization: `Bearer ${token}` }
    })

    const data = res?.data || {}
    healthDataList.value = data.list || []
    total.value = data.total || 0

    const elderly = elderlyList.value.find((e) => e.userId === selectedElderlyId.value)
    if (elderly) selectedElderly.value = elderly
  } catch (error) {
    console.error('获取健康数据失败', error)
    ElMessage.error('获取健康数据失败')
  } finally {
    loading.value = false
  }
}


const resetQuery = () => {
  query.value = { relationType: '', realName: '' }
  loadElderlyList()
}

/* ---------- 新增：健康详情 ---------- */
const openHealthDetailModal = async (elderly) => {
  detailElderly.value = elderly
  detailDialogVisible.value = true
  await loadDetailAlerts()
  await loadDetailHealth(1)
}

const loadDetailAlerts = async () => {
  const { data } = await axios.get(
      `${BASE_URL}/api/v1/health/alert/unhandled/${currentUser.value.userId}`,
      { headers: { Authorization: `Bearer ${token}` } }
  )
  detailAlerts.value = data.data.filter((a) => a.elderlyUserId === detailElderly.value.userId)
}

const loadDetailHealth = async (pageNum = 1) => {
  const { data } = await axios.get(`${BASE_URL}/api/v1/health/list`, {
    params: { elderlyUserId: detailElderly.value.userId, pageNum, pageSize: 5 },
    headers: { Authorization: `Bearer ${token}` }
  })
  detailHealthData.value = {
    list: data.data.list.map((h) => ({
      ...h,
      typeName: typeMap[h.dataType] || '未知',
      dataValue: h.dataValue,
      unit: h.unit,
      deviceName: h.deviceName,
      isNormal: h.isNormal === 1
    })),
    total: data.data.total,
    pageSize: 5
  }
}

const handleAlert = async (alertId) => {
  await axios.post(
      `${BASE_URL}/api/v1/health/alert/handle/${alertId}`,
      null,
      {
        params: { handleUserId: currentUser.value.userId },
        headers: { Authorization: `Bearer ${token}` }
      }
  )
  ElMessage.success('已标记为已处理')
  // 刷新状态
  await loadElderlyList()
  await loadDetailAlerts()
}

const exportDetailExcel = () => {
  const ws = XLSX.utils.json_to_sheet(
      detailHealthData.value.list.map((h) => ({
        指标: h.typeName,
        数值: h.dataValue,
        单位: h.unit,
        设备: h.deviceName,
        是否正常: h.isNormal ? '健康数据正常' : '健康数据异常'
      }))
  )
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '健康数据')
  XLSX.writeFile(wb, `${detailElderly.value.realName}_健康数据.xlsx`)
}

/* ---------- 生命周期 ---------- */
onMounted(() => {
  loadElderlyList()
})

/* ---------- 计算属性 ---------- */
const genderText = computed(() =>
    selectedElderly.value?.gender === 1 ? '男' : '女'
)
const age = computed(() => {
  if (!selectedElderly.value?.birthDate) return '--'
  return dayjs().year() - dayjs(selectedElderly.value.birthDate).year()
})
const avatarUrl = computed(() =>
    selectedElderly.value?.gender === 1
        ? 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
        : 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
)
const getTypeName = (type) => typeMap[type] || '未知'
const formatTime = (time) => dayjs(time).format('YYYY-MM-DD HH:mm')
</script>

<style scoped>
.card-grid-overview {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 25px;
  margin-bottom: 30px;
}

.card-grid-overview .el-card {
  width: 280px;
  height: 220px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fff;
  border: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  padding: 20px;
  box-sizing: border-box;
}

.card-grid-overview .el-card.abnormal {
  background: #ffecec;
  border-color: #f56c6c;
}

.card-grid-overview .disabled {
  opacity: 0.5;
  pointer-events: none;
}

.card-grid-overview .avatar {
  margin-bottom: 12px;
}

.card-grid-overview .name {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #303133;
}

.card-grid-overview .el-tag {
  margin-top: 4px;
}

.card-grid-overview .el-card:hover:not(.disabled) {
  transform: translateY(-4px);
}

/* 弹窗预警条 */
.alert-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 8px;
  background: #fff1f0;
  border-left: 4px solid #f56c6c;
}
</style>